package controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import util.RedisUtil;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/car")
public class CarRedisController {
    @Autowired
    RedisUtil redisUtil;

    @Autowired
    RedisTemplate redisTemplate;


    @RequestMapping("/addCar")
    public String  addCar(@RequestParam String userName,@RequestParam Integer pid,@RequestParam String productName,@RequestParam String productImg,@RequestParam Double productPrice){
//        System.out.println(userName+","+pid+","+productName+","+productImg+","+productPrice);
        /*购物车实现过程:
        * 1.判断用户是否有购物车,如何判断:通过key获取value的长度
        * 1)长度>0有购物车,2)=0没有购物车
        * 有购物车的情况:
        * 1)当前加入的商品购物车已存在=>不应该添加对象,而是把当前购物车数量+1
        * 2)当前加入的商品购物车不存在=>添加一个对象即可,数量默认为1个
        *
        * 2没有购物车:直接添加,数量默认为1个
        *
        * */

        //取用户购物车,无论用户购物车里是否有商品
        List<Object> list=redisUtil.lGet(userName,0,-1);
        if(list!=null){
            if(list.size()>0){//有购物车
                //假设购物车里商品的pid=>1
                boolean flag=false;
                for(int i=0;i<list.size();i++){
                    Product product=((Product) list.get(i));
                    if(String.valueOf(product.getPid()).equals(String.valueOf(pid))){//购物车里的pid等于当前的pid，说明当前商品已存在
                        flag=true;
                        product.setProductNum(product.getProductNum()+1);
                        redisUtil.lUpdateIndex(userName,i,product);
                        return "ok";
                    }
                }

                if(!flag){//当前商品不在购物车里
                    redisUtil.lSet(userName,new Product(pid,productName,productImg,productPrice,1));
                    return "ok";
                }
            }else{
                System.out.println("小else");
                redisUtil.lSet(userName,new Product(pid,productName,productImg,productPrice,1));
                return "ok";
            }
        }else{
            redisUtil.lSet(userName,new Product(pid,productName,productImg,productPrice,1));
            return "ok";
        }
        System.out.println(redisUtil.lGet(userName,0,-1));

        return "no";
    }



    @RequestMapping("/getUserCar")
    public List<Object> getUserCar(@RequestParam String userName){
        return redisUtil.lGet(userName,0,-1);
    }


    
}
